package com.hexacta.hrs;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

/**
 * Constant class for the application's version. If change to another package,
 * must modify line 26 with the new package path.
 * 
 * Used to check the database schema compatibility with the application object
 * model. Both must be equal for the application to run.
 * 
 * @author tpollak
 */
public class Version {

    public static final String SCHEMA_VERSION;

    private Version() {
        // Do not instantiate
    }

    static {
        String version = null;

        String pathToThisClass = Version.class.getResource("/com/hexacta/hrs/Version.class").toString();

        String manifestPath = pathToThisClass.substring(0, pathToThisClass.indexOf("!") + 1) + "/META-INF/MANIFEST.MF";
        // Queda este path:
        // jar:file:/C:/HRS-iandronowicz/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/hrs-intranet
        // /WEB-INF/lib/hrs-core.jar!/META-INF/MANIFEST.MF

        Manifest manifest = Version.getManifest(manifestPath);

        if (manifest != null) {
            Attributes a = manifest.getMainAttributes();
            version = a.getValue("Implementation-Version");
        } else {
            // hrs-core-2.0.13-SNAPSHOT.jar
            // Parseo y me quedo con 2.0.13-SNAPSHOT
            // String classStr = "hrs-core-";
            // version =
            // pathToThisClass.substring(pathToThisClass.indexOf(classStr) +
            // classStr.length(), pathToThisClass
            // .indexOf(".jar"));
            version = "2.1.2";
        }

        // SCHEMA_VERSION = version;
        SCHEMA_VERSION = "3.3.0";
    }

    /**
     * 
     * @param manifestPath
     * @return El manifest de la URL dada
     */
    private static Manifest getManifest(final String manifestPath) {
        try {
            return new Manifest(new URL(manifestPath).openStream());
        } catch (MalformedURLException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
    }

}
